/*
 * 调用的是本地的map服务器，如果是其他的服务器，需修改
 */
var defaultShopIcon = "/wcsi/img/defaultShop.png";
var defaultEventTypeIcon = "/wcsi/img/defaultEventType.png";
var arcGisUrl = "http://39.107.125.44:6080";
var map;
var tempgraphic;
var g_labels = "";
var g_textsearch = "", g_textvalue = "";
var g_value = "", g_left, g_right;
var arcTool, manhole_cover_p;
var hander;
var centerX = 106.638;// 120.206354450751;
var centerY = 26.684;// 30.0725834699399;
var toolbar;
var drawHandler;
var gsvc;// 测量面积
var partLayer;
var gridLayer;
var shopLayer;
var userLayer;
var text_graphic;
var dynamic;
var highLayer;
var gridCenterX = 106.62783532184868;
var gridCenterY = 26.686101063755615;
var interval;
var intervalflashTime;
var intervalflashTimeEvent;
var intervalflashTimeWarning;
var intervalflashTimePart;
var FlickerPointType = "reportFlickerPointType";
var showFlickerPointTyp = FlickerPointType;
var showFlickerEventPointType = "eventFlickerPointType";
var showFlickerWaringPointType = "warningFlickerPointType";
var socketList;
require([ "esri/map", "esri/Color", "esri/graphic", "esri/InfoTemplate",
		"esri/SpatialReference", "esri/renderers/HeatmapRenderer",
		// 控件
		"esri/dijit/OverviewMap", "esri/dijit/Scalebar",
		"esri/dijit/Measurement", "esri/units",
		// 图层
		"tdlib/TDTLayer", "tdlib/TDTAnnoLayer", "tdlib/TDT_ImgLayer",
		"tdlib/TDT_ImgAnnoLayer", "esri/layers/GraphicsLayer",
		"esri/layers/ArcGISDynamicMapServiceLayer",
		"esri/layers/ArcGISTiledMapServiceLayer", "esri/layers/FeatureLayer",
		// 图形要素
		"esri/geometry/Point", "esri/geometry/Polyline",
		"esri/geometry/Polygon", "esri/geometry/Circle",
		// 样式
		"esri/symbols/TextSymbol", "esri/symbols/SimpleMarkerSymbol",
		"esri/symbols/PictureMarkerSymbol", "esri/symbols/SimpleLineSymbol",
		"esri/symbols/SimpleFillSymbol",
		// 标签
		"esri/symbols/Font", "esri/layers/LabelClass",
		// 查询
		"esri/tasks/query", "esri/tasks/QueryTask", "esri/toolbars/draw",
		"esri/dijit/Popup", "esri/dijit/PopupTemplate", "dojo/dom",
		"dojo/dom-construct", "esri/tasks/GeometryService" ], function(Map,
		Color, Graphic, InfoTemplate, SpatialReference, HeatmapRenderer,
		OverviewMap, Scalebar, Measurement, Units, TDTLayer, TDTAnnoLayer,
		TDT_ImgLayer, TDT_ImgAnnoLayer, GraphicsLayer,
		ArcGISDynamicMapServiceLayer, ArcGISTiledMapServiceLayer, FeatureLayer,
		Point, Polyline, Polygon, Circle, TextSymbol, SimpleMarkerSymbol,
		PictureMarkerSymbol, SimpleLineSymbol, SimpleFillSymbol, Font,
		LabelClass, Query, QueryTask, Draw, Popup, PopupTemplate, dom,
		domConstruct, GeometryService) {
	$("#map").css({"height":+$("#right").height()+"px"}); 
	map = new Map("map", {
		
		slider : false,
		logo : false,
		showLabels : true,
		center : [ centerX, centerY ],
		zoom : 17,
		minZoom : 15,
		maxZoom : 18
	});
	var vec = new TDTLayer();
	var veca = new TDTAnnoLayer();
	var img = new TDT_ImgLayer();
	var imga = new TDT_ImgAnnoLayer();
	map.addLayer(vec);
	map.addLayer(veca);
	
	var url = arcGisUrl + "/arcgis/rest/services/ceshi3/MapServer";
	partLayer = new FeatureLayer(url + "/16", {
		mode:FeatureLayer.MODE_SNAPSHOT,
		outFields : [ "*" ],
		maxScale : 0,
		minScale : 4508.935440959931,
		visible : true,
		id : "partLayer"
	});
	map.addLayer(partLayer);

	partLayer.setMaxScale(0);
	partLayer.setMinScale(4508.935440959931);
	
	partLayer.on("mouse-over", function(evt) {
		map.setMapCursor('pointer');
	});
	partLayer.on("mouse-out", function(evt) {
		map.setMapCursor('default');
	});


	gsvc = new GeometryService(arcGisUrl
			+ "/arcgis/rest/services/Utilities/Geometry/GeometryServer");

	toolbar = new Draw(map);
	dojo.connect(partLayer, "onClick", showPartDetail);
});

//部件展示信息
function showPartDetail(evt){
	console.log("partLayer:click");
	if (evt.graphic) {
		console.log("part:click");
		var id = evt.graphic.attributes.id;
		$('#partModal').modal('show');
		showParticles();
		getPartInfo(id);
	}
};

function getPartInfo(id){
	var url=window.rootPath+"/ui/partShow/getPartRealInfo/"+id;
    jQuery.ajax({
        url:encodeURI(url),
        cache:false,
        type : "get",
        dataType:"json",
        success:function(data){
       	  	var count = data.count;
       	  	var html = '';
       	  	html += "<li>部件名称:"+"<span id='parts_name'>"+data.parts_name+'</span></li>';
       	  	html += "<li >设备类型:"+"<span id='partsname'>"+data.partsname+'</span></li>';
       	  	html += "<li >警告类型:"+"<span id='warnStatusName'>"+data.warnStatusName+'</span></li>';
       	  	html += "<li >警告说明:"+"<span id='warnExp'>"+data.warnExp+'</span></li>';
       	  	html += "<li >故障类型:"+"<span id='errorStatusName'>"+data.errorStatusName+'</span></li>';
       	  	html += "<li >故障说明:"+"<span id='errorExp'>"+data.errorExp+'</span></li>';
       	  	html += "<li >数据时间:"+"<span id='sendDate'>"+data.sendDate+'</span></li>';
       	  	
       	  	if(count > 0){
           	  	for(var i=0;i<count;i++){
           	  		var name = data['name'+i];
           	  		var value = data['value'+i] != null ? data['value'+i] : '';
           	  		var warning = data['warning'+i];
           	  		var warningTitle = data['warningTitle'+i];
           	  		var color ='';
           	  		var display = '';
           	  		if(warning){
           	  			color = 'red';
           	  			display = '';
           	  		}else{
           	  			color = 'white';
           	  			display = 'none';
           	  		}
           	  		
           	  		html += '<li>'+name+':'
       	  				+ '<span style="margin-right:10px;" id="value'+i+'">'+value+'</span><font style="color:'+color+';display:'+display+'" id="warningTitle'+i+'">'+warningTitle+'</font></li>';
           	  	}
       	  	}
       	  	$('#listShow').html(html);
       	  	setTimeout(function(){
       	  		stroll.bind( '#listShow' );
       	  	},500);
	       	// 防异步错误
	    		if(interval){
	    			clearInterval(interval);
	    			interval=null;
	    		}
	    		// 单位数据刷新
	    		interval = setInterval(function() {
	    			refreashPartInfo(id);
	    		}, 5000);
       	  	
        }
    });
};

function refreashPartInfo(id){
	var url=window.rootPath+"/ui/partShow/getPartRealInfo/"+id;
    jQuery.ajax({
        url:encodeURI(url),
        cache:false,
        type : "get",
        dataType:"json",
        success:function(data){
       	  	var count = data.count;
       	  	$('#parts_name').val(data.parts_name);
       	  	$('#partsname').val(data.partsname);
       	  	$('#warnStatusName').val(data.warnStatusName);
       	  	$('#warnExp').val(data.warnExp);
       	  	$('#errorStatusName').val(data.errorStatusName);
       	  	$('#errorExp').val(data.errorExp);
       	  	$('#sendDate').val(data.sendDate);
       	  	if(count > 0){
           	  	for(var i=0;i<count;i++){
           	  		var name = data['name'+i];
           	  		var value = data['value'+i] != null ? data['value'+i] : '';
           	  		var warning = data['warning'+i];
           	  		var warningTitle = data['warningTitle'+i];
           	  		var color ='';
           	  		var display = '';
           	  		if(warning){
           	  			color = 'red';
           	  			display = '';
           	  		}else{
           	  			color = 'white';
           	  			display = 'none';
           	  		}
           	  		$('#value'+i).html(value);
           	  		var warning = $('#warningTitle'+i);
           	  		warning.attr('style','color:'+color+';display:'+display);
           	  		warning.html(warningTitle);
           	  	}
       	  	}
        }
    })
};

function createPoint(data, symbolurl,width,height) {
	var symbol = new esri.symbol.PictureMarkerSymbol(symbolurl,width,height);

	var myPoint = {
		"geometry" : {
			"type" : "point",
			"x" : data.longitude,
			"y" : data.latitude,
			"spatialReference" : {
				"wkid" : 4326
			}
		},
		"attributes" : data,
		"symbol" : symbol
	};
	var geometry = {
		"type" : "point",
		"x" : data.longitude,
		"y" : data.latitude,
		"spatialReference" : {
			"wkid" : 4326
		}
	};

	var graphic = new esri.Graphic(myPoint);
	graphic.symbol = symbol;
	graphic.attributes = data;
	return graphic;
};

jQuery(document).ready(function () {
	setTimeout(function(){
		initParticles();
	},0)
	$(window).resize(function(){
		var rightHeight=$("#left").height()-$("#footer").height()-$("#header").height();
		$("#map").height(rightHeight);
		$("#map").css({"height":+$("#right").height()+"px"}); 
		
		var listh = $('#list-header').height();
		var listd = $('#partInfoDiv').height();
		$('#listShow').height(listd-listh);
	});
	
	var listh = $('#list-header').height();
	var listd = $('#partInfoDiv').height();
	$('#listShow').height(listd-listh);
	setTimeout(function(){
		getPartToMap();
	},1000)
});

function cleanLayer(){
	if(partLayer){
		partLayer.clear();
	}
	// 防异步错误
	if(interval){
		clearInterval(interval);
		interval=null;
	}
};
	
function getPartToMap(){
	var url=window.rootPath+"/ui/partShow/getPartList";
	jQuery.ajax({
		url:encodeURI(url),
		cache:false,
		type : "get",
		dataType:"json",
		success:function(data){
			var parts = data.parts;
			cleanLayer();
			$("#search").val('');
			for(var i=0;i<parts.length;i++){
				var partBaseInfo = parts[i];
				var part = partBaseInfo.part;
				var icon = part.iconAddress;
				
				if (icon && icon!='') {
					icon = window.rootPath + '/'+icon;
				}else{
					if(partBaseInfo.part&&partBaseInfo.part.partType&&partBaseInfo.part.partType.value=="1"){
						icon = window.rootPath + '/img/defaultTV.png';
					}else{
						icon = window.rootPath + '/img/defaultPart.png';
					}
					
				}
				var temp = createPoint(partBaseInfo, icon,20,20);
//				map.centerAndZoom(temp.geometry, map.getLevel());
				partLayer.add(temp);
			}
			
			//部件刷新检查
			//立即执行一次
			refreashPartStatus();
			// 防异步错误
			if(intervalflashTimePart){
				clearInterval(intervalflashTimePart);
				intervalflashTimeEvent=null;
			}
			// 单位数据刷新
			intervalflashTimePart = setInterval(function() {
				refreashPartStatus();
			}, 10000);

			// 防异步错误
			if(intervalflashTimeWarning){
				clearInterval(intervalflashTimeWarning);
				intervalflashTimeEvent=null;
			}
			// 单位数据刷新
			intervalflashTimeWarning = setInterval(function() {
				refreashFlickerWarningPoint();
			}, 75);
			
		}
	});
};

function refreashPartStatus(){
	var url=window.rootPath+"/ui/partShow/refreashPartStatus";
	jQuery.ajax({
		url:encodeURI(url),
		cache:false,
		type : "get",
		dataType:"json",
		success:function(data){
			var warnings = data.warnings;
			cleanWarningPoint();
			if(warnings){
				for(var i=0;i<warnings.length;i++){
					var temp = createFlickerWarningPoint(warnings[i]);
					partLayer.add(temp);
				}
			}
		}
	});
};

function createFlickerWarningPoint(data) {		
	var	symbol = new esri.symbol.SimpleMarkerSymbol(
				esri.symbol.SimpleMarkerSymbol.STYLE_CIRCLE, // 样式,STYLE_CIRCLE(●),STYLE_CROSS(+),STYLE_DIAMOND(◆),STYLE_SQUARE(■),STYLE_X(X)
				1, // 像素
				new esri.symbol.SimpleLineSymbol(
						esri.symbol.SimpleLineSymbol.STYLE_SOLID, // 样式,STYLE_DASH(破折号),STYLE_DASHDOT(点划线),STYLE_DASHDOTDOT,STYLE_DOT(点),STYLE_NULL,STYLE_SOLID(实线)
						new dojo.Color([ 255, 0, 0 ]), 0.1), // 颜色 1 // 像素 ),
				new dojo.Color([ 255, 0, 0, 1 ]) // 颜色和透明度
		);
	var myPoint = {
		"geometry" : {
			"type" : "point",
			"x" : data.longitude,
			"y" : data.latitude,
			"spatialReference" : {
				"wkid" : 4326
			}
		},
		"attributes" : data,
		"symbol" : symbol
	};
		var graphic = new esri.Graphic(myPoint);
		 graphic.symbol = symbol;
		 graphic.attributes = data;
		 graphic.pointType = showFlickerWaringPointType;
	return graphic;
};

function cleanWarningPoint(){
	var len =partLayer.graphics.length;
	var graphics = partLayer.graphics;
	for (var i = len - 1; i >= 0; i--) {
		var graphic = graphics[i];
		if (graphic.pointType == showFlickerWaringPointType ) {
			partLayer.remove(graphics[i]);
		}
	}
};

function refreashFlickerWarningPoint() {
	var len =partLayer.graphics.length;
	var graphics = partLayer.graphics;
	for (var i = 0; i < len; i++) {
		var graphic = graphics[i];
		if (graphic.pointType == showFlickerWaringPointType ) {
			var symbol = graphic.symbol;
			if (symbol) {
				symbol.color.a -= 0.05;
				symbol.setSize(symbol.size + 8);
	
				if (symbol.color.a <= 0) {
					symbol.color.a = 1;
					symbol.setSize(1);
				}
				graphic.setSymbol(symbol);
			}
		}
	}
};



function getcurrentGraphicsByValue(txt) {
	if(txt==undefined||txt==""){
		return;
	}
	//部件检索
	var graphics = partLayer.graphics;
	for (var i = 0; i < graphics.length; i++) {
		if (graphics[i] && graphics[i].geometry.type == "point") {
			if (graphics[i].attributes) {
				if (graphics[i].attributes.partName
						&& graphics[i].attributes.partName.indexOf(txt) != -1) {
					highLayer.add(createPoint(graphics[i].attributes, "../img/highSelect.png",40,40));
					continue;
				} else if (graphics[i].attributes.partIdentify
						&& graphics[i].attributes.partIdentify.indexOf(txt) != -1) {
					highLayer.add(createPoint(graphics[i].attributes, "../img/highSelect.png",40,40));
					continue;
				} else if (graphics[i].attributes.manufacturer
						&& graphics[i].attributes.manufacturer.indexOf(txt) != -1) {
					highLayer.add(createPoint(graphics[i].attributes, "../img/highSelect.png",40,40));
					continue;
				} else if (graphics[i].attributes.deviceIdentify
						&& graphics[i].attributes.deviceIdentify
								.indexOf(txt) != -1) {
					highLayer.add(createPoint(graphics[i].attributes, "../img/highSelect.png",40,40));
					continue;
				} else if (graphics[i].attributes.hierarchy
						&& graphics[i].attributes.hierarchy.groupName
								.indexOf(txt) != -1) {
					highLayer.add(createPoint(graphics[i].attributes, "../img/highSelect.png",40,40));
					continue;
				}
			}
		}
	}
};

$("body").on("click",'.searchBtn',function () {
	getcurrentGraphicsByValue($("#search").val());
});

$("body").on("click",'.resetBtn',function () {
	$("#search").val('');
});

$("body").on("click",'#closePartInfo',function () {
	hideParticles();
});

$(window).unload(function(){  
	clearuserLayer();
}); 

function hideParticles(){
	var overlay = $('#partInfo');
	overlay.removeClass(overlay.data('return')).addClass(overlay.data('hover'));
	
	setTimeout(function(){
		$('#partInfoDiv').hide();
	},500);
	
	// 防异步错误
	if(interval){
		clearInterval(interval);
		interval=null;
	};
};

function initParticles(){
	$('#partInfoDiv').hide();
};

function showParticles(){
	$('#partInfoDiv').show();
	var overlay = $('#partInfo');	
	overlay.removeClass(overlay.data('hover')).addClass(overlay.data('return'));
};
